package com.justRun;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.androidplot.Plot;
import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYStepMode;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
import com.justRun.R;

import android.os.Bundle;
import android.os.SystemClock;

import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Typeface;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class PathActivity extends MapActivity {
	MapView mapView;
	private List<Overlay> mapOverlays;
	private FileManager fm;
	private Projection projection; 
	private MapController mc;
	private GeoPoint gP;
	private double temps = 0, vitesse = 0, distance = 0, calories = 0;
	private ArrayList<Double> tableauVitesses = new ArrayList<Double>(), tableauTemps = new ArrayList<Double>();
	private String nomParcours = "test.txt";
	private TextView textDistance, textVitesse, textCalories, textUniteDistance;
	private DecimalFormat df2 = new DecimalFormat(), df1 = new DecimalFormat(), df0 = new DecimalFormat();
	private LinearLayout pathMainLayout;
	private int color1 = 0x883af24b;
	private int positionEcran = 0;
	private SimpleXYSeries serie;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pathglobal);
		initLayout();
		majPaths();
		initStyle();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		if(!(new FileManager(this, "path.txt").fileExists())) {
			ViewFlipper vf = (ViewFlipper) findViewById(R.id.details);
			for(int i = 0; i < positionEcran; i++) {
				vf.showPrevious();				
			}
			positionEcran = 0;
		}
		majPaths();
	}

	private void initLayout() {
		pathMainLayout = ((LinearLayout) findViewById(R.id.pathMainLayout));
		
		((Button) findViewById(R.id.homeButtonPath1)).setOnClickListener(home);
		((Button) findViewById(R.id.runButtonPath1)).setOnClickListener(run);
		((Button) findViewById(R.id.statsButtonPath1)).setOnClickListener(stats);

		((Button) findViewById(R.id.homeButtonPath2)).setOnClickListener(home);
		((Button) findViewById(R.id.runButtonPath2)).setOnClickListener(run);
		((Button) findViewById(R.id.statsButtonPath2)).setOnClickListener(stats);
		((Button) findViewById(R.id.buttonBackPath)).setOnClickListener(backToPath);
		((Button) findViewById(R.id.buttonGoMap)).setOnClickListener(goToMap);
		textDistance = (TextView) findViewById(R.id.textDistance);
		textUniteDistance = (TextView) findViewById(R.id.textUniteDistance);
		textVitesse = (TextView) findViewById(R.id.TextVitesse);
		textCalories = (TextView) findViewById(R.id.TextCalories);

		((Button) findViewById(R.id.homeButtonPath3)).setOnClickListener(home);
		((Button) findViewById(R.id.runButtonPath3)).setOnClickListener(run);
		((Button) findViewById(R.id.statsButtonPath3)).setOnClickListener(stats);
		((Button) findViewById(R.id.buttonBackMap)).setOnClickListener(backToStats);
	}

	private void initStyle() {
		df2.setMaximumFractionDigits(2);
		df1.setMaximumFractionDigits(1);
		df0.setMaximumFractionDigits(0);
		TextView texteView = (TextView) findViewById(R.id.chronometer1);
		Typeface font = Typeface.createFromAsset(getAssets(), "digital.ttf");
		texteView.setTypeface(font);
		textDistance.setTypeface(font);
		textCalories.setTypeface(font);
		textVitesse.setTypeface(font);
		XYPlot graphe = ((XYPlot) findViewById(R.id.mySimpleXYPlot));
		graphe.disableAllMarkup();
		graphe.setRangeLabel("Vitesse (km/h)");
		graphe.setBorderStyle(Plot.BorderStyle.NONE, null, null);
		graphe.getBorderPaint().setColor(Color.TRANSPARENT);
		graphe.getBackgroundPaint().setAlpha(0);
		graphe.getGraphWidget().getGridBackgroundPaint().setAlpha(0);
		graphe.getGraphWidget().getGridLinePaint().setColor(0x88ffffff);
		graphe.getGraphWidget().getBackgroundPaint().setAlpha(0);
		graphe.getGraphWidget().getDomainLabelPaint().setColor(0xffffffff);
		graphe.getGraphWidget().getRangeLabelPaint().setColor(0xffffffff);
		graphe.setDomainLabel("Temps (minutes)");
		graphe.setDomainValueFormat(df0);
		graphe.setRangeValueFormat(df1);
		graphe.getTitleWidget().setVisible(false);
		graphe.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 1);
	}

	private void majStats() {
		majDonnees();
		majAffichageChrono();
		textDistance.setText(df2.format(distance));
		if (distance < 1) { 
			textUniteDistance.setText("m");
			textDistance.setText(df2.format(distance * 1000));			
		}
		else {
			textUniteDistance.setText("km");
			textDistance.setText(df2.format(distance));	
		}
		textVitesse.setText(df2.format(vitesse));
		textCalories.setText(df1.format(calories));
		majGraphique();
	}

	private void majMap() {
		mapView = (MapView) findViewById(R.id.mapView);
		mapView.setBuiltInZoomControls(true);
		mapOverlays = mapView.getOverlays();        
		projection = mapView.getProjection();
		mapOverlays.add(new MyOverlay(lectureCoords()));
		mc = mapView.getController();
		mc.setCenter(gP);
		mc.setZoom(17);
	}

	private OnClickListener backToPath = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			ViewFlipper vf = (ViewFlipper) findViewById(R.id.details);
			vf.showPrevious();
			majPaths();
			positionEcran = 0;
		}
	};

	private OnClickListener goToMap = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			ViewFlipper vf = (ViewFlipper) findViewById(R.id.details);
			vf.showNext();
			majMap();
			positionEcran = 2;
		}
	};

	private OnClickListener backToStats = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			ViewFlipper vf = (ViewFlipper) findViewById(R.id.details);
			vf.showPrevious();
			positionEcran = 1;
		}
	};
	
	private class GoToStats implements OnClickListener {
		String nomFichier;
		public GoToStats(String nom) {
			nomFichier = nom;
		}

		@Override
		public void onClick(View v) {
			nomParcours = nomFichier;
			ViewFlipper vf = (ViewFlipper) findViewById(R.id.details);
			vf.showNext();
			majStats();
			positionEcran = 1;
		}
	}

	private OnClickListener home = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			Intent myIntent = new Intent(arg0.getContext(),HomeActivity.class);
			startActivity(myIntent);
			finish();
		}
	};

	private OnClickListener stats = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			Intent myIntent = new Intent(arg0.getContext(),StatsActivity.class);
			startActivity(myIntent);
			finish();
		}
	};

	private OnClickListener run = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			Intent myIntent = new Intent(arg0.getContext(),RunActivity.class);
			startActivity(myIntent);
			finish();
		}
	};

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	class MyOverlay extends Overlay {

		private ArrayList<Integer> coords;

		public MyOverlay(ArrayList<Integer> coo){
			this.coords=coo;
		}   

		public void draw(Canvas canvas, MapView mapv, boolean shadow){
			super.draw(canvas, mapv, shadow);

			Paint mPaint = new Paint();
			mPaint.setAntiAlias(true);
			mPaint.setDither(true);
			mPaint.setColor(Color.RED);
			mPaint.setStyle(Paint.Style.STROKE);
			mPaint.setStrokeJoin(Paint.Join.ROUND);
			mPaint.setStrokeCap(Paint.Cap.ROUND);
			mPaint.setStrokeWidth(3);
			GeoPoint gP1 = new GeoPoint(0,0);
			GeoPoint gP2 = new GeoPoint(0,0);
			Point p1 = new Point();
			Point p2 = new Point();
			Path path = new Path();
			for (int i=0; i<coords.size() - 3; i=i+2){
				gP1 = new GeoPoint(coords.get(i), coords.get(i+1));
				gP2= new GeoPoint(coords.get(i+2), coords.get(i+3));
				projection.toPixels(gP1, p1);
				projection.toPixels(gP2, p2);
				path.moveTo(p2.x, p2.y);
				path.lineTo(p1.x,p1.y);
				System.out.println("Point 1 : " + gP1);
				System.out.println("Point 2 : " + gP2);
			}
			canvas.drawPath(path, mPaint);
		}
	}

	private void majDonnees() {
		fm = new FileManager(this, nomParcours);
		double k = 1;
		XYPlot graphe = ((XYPlot) findViewById(R.id.mySimpleXYPlot));
		try {
			tableauVitesses = new ArrayList<Double>();
			tableauTemps = new ArrayList<Double>();
			fm.startReading();
			System.out.println("MISE A JOUR DES DONNEES A PARTIR DE : " + nomParcours);
			temps = Double.parseDouble(fm.readLine());
			distance = Double.parseDouble(fm.readLine());
			calories = Double.parseDouble(fm.readLine());
			vitesse = Double.parseDouble(fm.readLine());
			if((temps/60000) < 1) {
				k = 60;
				graphe.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 6);
				graphe.setDomainLabel("Temps (secondes)");
			} else if((temps/60000) < 10) {
				graphe.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 1);
				graphe.setDomainLabel("Temps (minutes)");			
			} else if((temps/60000) < 30) {
				graphe.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 2);
				graphe.setDomainLabel("Temps (minutes)");			
			} else if((temps/60000) < 60) {
				graphe.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 5);
				graphe.setDomainLabel("Temps (minutes)");			
			} else {
				graphe.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 10);
				graphe.setDomainLabel("Temps (minutes)");			
			}
			try {
				while (fm.readLine() != null) {
					fm.readLine();
					tableauVitesses.add((Double.parseDouble(fm.readLine())));
					tableauTemps.add(k*(Double.parseDouble(fm.readLine()) / 60000));
				}
				fm.stopReading();
				System.out.println("DONNEES MISE A JOUR A PARTIR DE : " + nomParcours);
			} catch (Exception e) {
				e.printStackTrace();
				fm.stopReading();
			} 
		} catch (Exception e) {
			e.printStackTrace();
			fm.stopReading();
		}
	}

	private ArrayList<Integer> lectureCoords() {
		ArrayList<Integer> res = new ArrayList<Integer>();
		fm = new FileManager(this, nomParcours);
		fm.startReading();
		fm.skipLine(4);
		String ligne = "";
		try {
			while ((ligne = fm.readLine()) != null) {
				res.add((int)(1000000*Double.parseDouble(ligne)));
				res.add((int)(1000000*Double.parseDouble(fm.readLine())));
				fm.skipLine(2);
			}
			fm.stopReading();
			gP = new GeoPoint(res.get(0), res.get(1));
		} catch (Exception e) {
			e.printStackTrace();
			fm.stopReading();
		}
		return res;
	}

	private void ajouterLigne(String nom, String date, String nomFichier) {
		LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		ParcoursLayout pL = new ParcoursLayout(this);
		pL.onClick(new GoToStats(nomFichier));
		pL.setLeftText(nom);
		pL.setMiddleText(date);
		pathMainLayout.addView(pL.getLayout(),param);
	}
	
	private void majPaths() {
		pathMainLayout.removeAllViews();
		FileManager fmTemp = new FileManager(this, "path.txt");
		fmTemp.startReading();
		String nom = "";
		try {
			while((nom = fmTemp.readLine()) != null) {
				ajouterLigne(nom, fmTemp.readLine(), fmTemp.readLine() + ".txt");
			}
			fmTemp.stopReading();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	private void majAffichageChrono() {
		Chronometer chrono = (Chronometer) findViewById(R.id.chronometer1);
		chrono.setBase((long) (SystemClock.elapsedRealtime() - temps));
		CharSequence text = chrono.getText();
		if (text.length() == 5) {
			chrono.setText("00:" + text);
		} else if (text.length() == 7) {
			chrono.setText("0" + text);
		}
	}
	
	private void majGraphique() {
		XYPlot graphe =((XYPlot) findViewById(R.id.mySimpleXYPlot));
		if (!graphe.isEmpty()) {
			graphe.removeSeries(serie);
		}
		serie = new SimpleXYSeries(tableauVitesses, tableauTemps, graphe.getDomainStepValue());
		graphe.addSeries(serie,
		        		new LineAndPointFormatter(Color.rgb(255, 255, 255), null, color1));
		graphe.setRangeUpperBoundary(serie.getVMax(), BoundaryMode.FIXED);
		graphe.setRangeStep(XYStepMode.INCREMENT_BY_VAL, (serie.getVMax() / 6));
	}
}
